﻿#region 文件信息

/*===================================================
* 类名称: ValidationBaseModel
* 类描述:
* 创建人: YangCheng
* 创建时间: 2022/5/18 9:49:28
* 修改人:
* 修改时间:
* 版本： @version 1.0
=====================================================*/

#endregion

namespace Vampirewal.Core.Models;

/// <summary>
/// 数据验证模型基类
/// </summary>
public class ValidationBaseModel : TopModel, IDataErrorInfo
{
    private string _errorStr;

    /// <summary>
    /// 错误信息（界面显示用）
    /// </summary>
    public string Error => _errorStr;

    /// <summary>
    ///
    /// </summary>
    /// <param name="columnName"></param>
    /// <returns></returns>
    public string this[string columnName]
    {
        get
        {
            Type type = GetType();
            PropertyInfo property = type.GetProperty(columnName);
            object[] customAttributes = property.GetCustomAttributes(inherit: false);
            object value = property.GetValue(this, null);
            object[] array = customAttributes;
            foreach (object obj in array)
            {
                ValidationAttribute validationAttribute = obj as ValidationAttribute;
                try
                {
                    if (validationAttribute != null && !validationAttribute.IsValid(value))
                    {
                        _errorStr = validationAttribute.ErrorMessage;
                        return validationAttribute.ErrorMessage;
                    }
                }
                catch (Exception)
                {
                    return "验证异常";
                }
            }

            _errorStr = string.Empty;
            return string.Empty;
        }
    }

    /// <summary>
    /// 验证是否合法（只验证带有验证标记的属性）
    /// </summary>
    /// <param name="ignoreProperties">自定义排除属性</param>
    /// <returns></returns>
    public bool IsValidation(params string[] ignoreProperties)
    {
        Type type = GetType();
        PropertyInfo[] properties = type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
        PropertyInfo[] array = properties;
        foreach (PropertyInfo propertyInfo in array)
        {
            if (ignoreProperties?.Contains(propertyInfo.Name) ?? false)
            {
                continue;
            }

            object[] customAttributes = propertyInfo.GetCustomAttributes(inherit: false);
            object value = propertyInfo.GetValue(this, null);
            object[] array2 = customAttributes;
            foreach (object obj in array2)
            {
                ValidationAttribute validationAttribute = obj as ValidationAttribute;
                if (validationAttribute != null && !validationAttribute.IsValid(value))
                {
                    _errorStr = validationAttribute.ErrorMessage;
                    return false;
                }
            }
        }

        return true;
    }
}